package com.zhoug.common3.filters;

import android.text.InputFilter;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.AutoCompleteTextView;

import com.zhoug.common3.utils.LogUtils;
import com.zhoug.common3.utils.StringUtils;

/**
 * 禁止输入中文过滤器
 *
 * @Author: zhoug
 * @Date: 2023/1/4
 * @Description:
 */
public class NoChineseInputFilter implements InputFilter {
    private static final String TAG = ">>>NoChineseInputFilter";
    private static boolean DEBUG = true;
    private static final char CHINESE_UNICODE_START = '\u4E00';
    private static final char CHINESE_UNICODE_END = '\u9FA5';
    private boolean allowSpace = true;//是否允许输入空格

    public NoChineseInputFilter() {
    }

    public NoChineseInputFilter(boolean allowSpace) {
        this.allowSpace = allowSpace;
    }

    /**
     * 当缓冲区要使用source的[start - end)范围内的内容替换dest的[dstart - dend)范围内的内容
     *
     * @param source 输入的内容,若是删除动作，则为空字符
     * @param start  输入内容的起始索引，始终为0
     * @param end    输入内容的长度,删除时为0
     * @param dest   原先显示的内容
     * @param dstart 被替换的内容在输入框中的起始位置(包含)
     * @param dend   被替换的内容在输入框中的结束位置(不包含)
     * @return 返回null:表示接受原本的输入source;返回空字符串"":放弃本次输入;返回指定内容
     */
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (DEBUG) {
            LogUtils.d(TAG, "source:" + source + ",start:" + start + ",end:" + end + ",dest:" + dest + ",dstart:" + dstart + ",dend:" + dend);
        }
        if (source == null || source.length() <= 0) {
            return null;
        }
        //非中文结果
        StringBuilder notChineseStringBuilder = new StringBuilder();
        //标记是否是原来的数据
        boolean isOriginal = true;
        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            if (!StringUtils.isChinese(c) && (allowSpace || !StringUtils.isWhitespace(c))) {
                notChineseStringBuilder.append(c);
            } else {
                isOriginal = false;
            }
        }
        //数据无改变,不过滤
        if (isOriginal) {
            return null;
        }
        String notChineseStr = notChineseStringBuilder.toString();
        if (DEBUG) {
            LogUtils.d(TAG, "过滤后的输入内容:"+notChineseStr);
        }
        //setSpan (0 ... 12) ends beyond length 10
        if (source instanceof Spanned) {
            SpannableString sp = new SpannableString(notChineseStr);
            TextUtils.copySpansFrom((Spanned) source, start, notChineseStr.length(), null, sp, 0);
            return sp;
        }
        return notChineseStr;
    }





}
